//
//  UIApplication+KYExtension.swift
//  KFManager
//
//  Created by kingly on 2016/11/15.
//  Copyright © 2016年 kingly inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. All rights reserved.
//

import UIKit

// MARK: - UIApplication

public extension UIApplication {
    
    /// current AppDelegate
    ///
    /// - Returns: Return current AppDelegate
    func ky_appDelegate() -> UIApplicationDelegate {
        return UIApplication.shared.delegate!
    }
  
    /// Get current UIViewController
    ///
    /// - Returns: return current UIViewController
//    func ky_currentViewController() -> UIViewController {
//        let window = self.ky_appDelegate().window
//        var viewController = window!!.rootViewController
//        
//        while ((viewController?.presentedViewController) != nil) {
//            viewController = viewController?.presentedViewController
//            
//            
//            
//            if ((viewController?.isKindOfClass(UINavigationController.classForCoder())) == true) {
//                viewController = (viewController as! UINavigationController).visibleViewController
//            } else if ((viewController?.isKindOfClass(UITabBarController.classForCoder())) == true) {
//                viewController = (viewController as! UITabBarController).selectedViewController
//            }
//        }
//        
//        return viewController!;
//    }
//    func ky_currentViewController() -> UIViewController {
//        var result : UIViewController?
//        var window = self.ky_appDelegate().window
//        if ((window??.windowLevel = UIWindowLevelNormal) != nil) {
//            let windows = UIApplication.shared.windows
//            for win:UIWindow in windows {
//            if win.windowLevel == UIWindowLevelNormal   {
//                    window = win
//                    break
//                }
//            }
//        }
//
//        let nextResponder = window??.subviews[0].next
//        if nextResponder!.isKindOfClass(UIViewController) {
//            let parNV = nextResponderas?;UINavigationController
//            let tabar = parNV?.topViewControlleras?UITabBarController
//            let childNV = (tabar!.selectedViewControlleras?UINavigationController)!
//            result = childNV.visibleViewController
//        }else{
//            result = window?.rootViewController
//        }
//        return result!
//    }
  

    
}


// MARK: - snapShot

public extension UIApplication {
    
    /// 快照
    ///
    /// - Parameter inView: 当前视图
    /// - Returns: 返回快照的图片
    func ky_snapShot(inView: UIView) -> UIImage {
        UIGraphicsBeginImageContext(inView.bounds.size)
        inView.layer.render(in: UIGraphicsGetCurrentContext()!)
        let snapShot: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return snapShot
    }
    
}

// MARK: - App Version Related

public extension UIApplication {
    

    /// 当前app的版本
    func ky_appVersion() -> String {
        let infoDict = Bundle.main.infoDictionary! as Dictionary<String, AnyObject>
        return infoDict["CFBundleShortVersionString"] as! String
    }
  
   /// 获得 CFBundleVersion
   func ky_appBuildVersion() -> String {
     let infoDict = Bundle.main.infoDictionary! as Dictionary<String, AnyObject>
     return infoDict["CFBundleVersion"] as! String
   }
  
  
    
//    /**
//     current App Version released in AppStore
//     
//     - parameter appId: appId in AppStore
//     
//     - returns: lastest appVersion in AppStore
//     */
//    func cs_appVersionInAppStore(appId: String) -> String {
//        var appVersion = ""
//        
//        let url = "https://itunes.apple.com/lookup?id=\(appId)"
//        let request = NSURLRequest(url: NSURL(string: url)! as URL)
//        
//        let semaphore = DispatchSemaphore(value: 0)
//        
//        let dataTask = URLSession.shared.dataTask(with: request as URLRequest)
//        { (data, response, error) in
//            do {
//                let jsonData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
//                if let results = jsonData["results"]! {
//                    assert(results.count != 0, "results should not be null")
//
//                    appVersion = results.firstObject!?["version"]! as! String
//                }
//                
//                semaphore.signal()
//                
//            } catch {
//            
//            }
//        }
//        dataTask.resume()
//        
//        dispatch_semaphore_wait(semaphore,dispatch_time_t(DispatchTime.distantFuture))
//        
//        return appVersion
//    }
//    
//    /**
//     Check whether this version of running App released or not.
//     For example:
//     Version of running App is 1.3, and app version in AppStore is 1.2,
//     then, this method will return false.
//     Several days later, app version in AppStore promotes to be 1.3 or 1.4,
//     then this method will return true.
//     
//     - parameter appId: appId in AppStore
//     
//     - returns: true or false
//     */
//    func cs_isRunningAppVersionReleased(appId: String) -> Bool {
//        let appVersionInAppStore = self.cs_appVersionInAppStore(appId: appId)
//        
//        if self.cs_appVersion().compare(appVersionInAppStore) != .OrderedDescending {
//            return true
//        }
//        
//        return false
//    }
    
}
